//package IAA;

import java.io.*;
import java.util.*;

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;
import javax.swing.text.*;
import javax.swing.event.*;
import javax.swing.border.*; 
import javax.swing.table.TableColumn;
import javax.swing.table.DefaultTableModel;

/**
 * To Do:
 * make the GUI more attractive
 * prevent the error that is going on
 * add more options
 * unite MAE, MAI, and IAA under META-MAX
 * convert the whole thing into a web service
 * make texty scrollable (or perhaps alter the appearance a bit)
 */

public class AgreeGui extends JPanel
{	

	//some global variables, particularly options to be passed via
	//command line wrapper
	//the "Options" menu will be instrumental here
	
	boolean modeExtent, matchLax; //changes here should cause menu updating
	int numberB;
	
	String dirName;
	String goldStandard;
	
	JMenuBar bar;
	JMenu file, options;
	JTextArea texty;
	JButton doIt;

	public AgreeGui()
	{
		super(new BorderLayout());
		
		modeExtent = true;
		matchLax = true;
		
		numberB = 6;
		
		doIt = new JButton("Execute");
		doIt.addActionListener(new Executioner());
		texty = new JTextArea(5, 20);
		texty.setEditable(false);
		//make texty prettier
		//maybe place current directory in a separate window? that would be sexy.
		
		bar = new JMenuBar();
		
		createMenus();
		
		this.add(bar, BorderLayout.NORTH);
		//this.setMenuBar(bar);
		this.add(texty, BorderLayout.CENTER);
		add(doIt, BorderLayout.SOUTH);
	}
	
	/**
	 * Ancillary functions!
	 */
		
	private void createMenus()
	{
		try
		{
			bar.remove(file);
			bar.remove(options);
		}
		catch (Exception e) {}
		//bar = new JMenuBar();
		file = createFileMenu();
		options = createOptionsMenu();
		bar.add(file);
		bar.add(options);
		bar.updateUI();
	}
	 
	private JMenu createFileMenu()
	{
		JMenu menu = new JMenu("File");
		JMenuItem open = new JMenuItem("Select Directory");
		open.setActionCommand("Find Directory");
		JMenuItem outp = new JMenuItem("Save Output");
		outp.setActionCommand("Save Output");
		
		open.addActionListener(new whereIsIt());
		outp.addActionListener(new whereIsIt());
		
		menu.add(open);
		menu.add(outp);
		
		return menu;
	}
	
	private JMenu createOptionsMenu()
	{
		JMenuItem item;
		JRadioButtonMenuItem rad;
		JMenu menu = new JMenu("Options");
		
		JMenu mode = new JMenu("Entity Type");
		mode.setMnemonic(KeyEvent.VK_M);
		ButtonGroup group = new ButtonGroup();	
		rad = new JRadioButtonMenuItem("Extents");
		rad.setMnemonic(KeyEvent.VK_E);
		rad.setSelected(modeExtent);
		rad.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, ActionEvent.ALT_MASK));
		rad.addActionListener(new optionBuddy());
		rad.setActionCommand("Extent");
		group.add(rad);
		mode.add(rad);
		rad = new JRadioButtonMenuItem("Links");
		rad.setMnemonic(KeyEvent.VK_L);
		rad.setSelected(!modeExtent);
		rad.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, ActionEvent.ALT_MASK));
		rad.addActionListener(new optionBuddy());
		rad.setActionCommand("Link");
		group.add(rad);
		mode.add(rad);
		menu.add(mode);
		
		item = new JMenuItem("Gold Standard");
		item.setEnabled(!modeExtent);
		item.addActionListener(new whereIsIt());
		item.setActionCommand("Gold Style");
		menu.add(item);
		
		menu.addSeparator();
		mode = new JMenu("Extent Matching");
		mode.setMnemonic(KeyEvent.VK_Q);
		group = new ButtonGroup();	
		rad = new JRadioButtonMenuItem("Lax");
		rad.setMnemonic(KeyEvent.VK_X);
		rad.setSelected(matchLax);
		rad.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.ALT_MASK));
		rad.addActionListener(new optionBuddy());
		rad.setActionCommand("Lax");
		group.add(rad);
		mode.add(rad);
		rad = new JRadioButtonMenuItem("Strict");
		rad.setMnemonic(KeyEvent.VK_S);
		rad.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.ALT_MASK));
		rad.setSelected(!matchLax);
		rad.addActionListener(new optionBuddy());
		rad.setActionCommand("Strict");
		group.add(rad);
		
		for (Enumeration<AbstractButton> g = group.getElements(); g.hasMoreElements();)
		{
			g.nextElement().setEnabled(modeExtent);
		}
		
		mode.add(rad);
		menu.add(mode);
		
		return menu;
	}
	
	/**
	 * I may need a "create submenu" method to encapsulate the process
	 * above and obviate excessive repetition
	 */
	
	
	
	/**
	 * Listeners! They are so attentive <3
	 */
	
	private class whereIsIt implements ActionListener
	{
		public void actionPerformed(ActionEvent e)
		{
			if (e.getActionCommand().equals("Find Directory"))
			{
				JFileChooser findDir = new JFileChooser(".");
				findDir.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
				int rVal = findDir.showOpenDialog(AgreeGui.this);
				if (rVal == JFileChooser.APPROVE_OPTION)
				{
					dirName = findDir.getSelectedFile().getAbsolutePath();
					//dirName = findDir.getSelectedFile().getName();
					texty.setText("Current Directory: " + dirName + "\n\n");
				}
			}
			
			else if (e.getActionCommand().equals("Save Output"))
			{
				JFileChooser saveOut = new JFileChooser(".");
				saveOut.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
				int rVal = saveOut.showSaveDialog(AgreeGui.this);
				if (rVal == JFileChooser.APPROVE_OPTION)
				{
					File file = saveOut.getSelectedFile();
					String fname = file.getAbsolutePath();
					if(!file.getAbsolutePath().endsWith(".txt"))
					{
						file = new File(fname + ".txt");
					}
					try (BufferedWriter out = 
						new BufferedWriter(new FileWriter(
						file)))
					{
						out.write(texty.getText());
					}
					catch (Exception ex)
					{
						//how???
						displayProblemPopup();
					}
				}
			}
			
			else if (e.getActionCommand().equals("Gold Style"))
			{
			
			}
		}
	}
	
	private void displayProblemPopup()
	{
	}
	
	private class optionBuddy implements ActionListener
	{
		public void actionPerformed(ActionEvent e)
		{
			if (e.getActionCommand().equals("Extent"))
			{
				modeExtent = true;
				createMenus();
			}
			
			else if (e.getActionCommand().equals("Link"))
			{
				modeExtent = false;
				createMenus();
			}
			
			else if (e.getActionCommand().equals("Lax"))
			{
				matchLax = true;
				createMenus();
			}
			
			else if (e.getActionCommand().equals("Strict"))
			{
				matchLax = false;
				createMenus();
			}
		}
	}
	
	private class Executioner implements ActionListener
	{
		public void actionPerformed(ActionEvent e)
		{
			execute();
		}
	}
	
	/**
	 * Python wrapper methods! "Pythongs," if you will.
	 */
	
	private void execute()
	{
		//String[] args = new String[numberB]; //for when more options exist
		String[] args = {"python", "IAA.py", dirName, "-m",
			modeExtent ? "extent" : "link", matchLax ? "-l" : "-s"};
		
		try
		{
			Process pr = Runtime.getRuntime().exec(args);
			BufferedReader inp = new BufferedReader(new InputStreamReader(pr.getInputStream()));
			String outp = null;
			while((outp=inp.readLine()) != null)
			{
				texty.append(outp);
				texty.append("\n");
			}
		}
		
		catch(Exception e)
		{
			for(int i = 0; i < numberB; i++)
			{
				texty.append(args[i] + (i + 1 == numberB ? "\n" : " "));
			}
			StringWriter babby = new StringWriter();
			e.printStackTrace(new PrintWriter(babby));
			texty.append(babby.toString() + "\n\n");
		}
	}
	
	/**
	 * Sine qua non!
	 */

	private static void createAndShowGUI()
	{
		JFrame frampton = new JFrame("Inter-Annotator Agreement");
		frampton.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		JComponent cp = new AgreeGui();
		cp.setOpaque(true); 
		frampton.setContentPane(cp);

		frampton.pack();
		frampton.setSize(450,250);
		frampton.setVisible(true);
	}
	
	public static void main(String[] args)
	{
		javax.swing.SwingUtilities.invokeLater
		(
			new Runnable() 
			{
				public void run() 
				{
					createAndShowGUI();
				}
			}
		);
	}
}
